#include "mqttLocal.h"
#include "logger.h"
#include "threadLock.h"
#include "settingsManager.h"

#include <unistd.h>


T_MQTT_MANAGER g_local_mqtt;
T_THREAD_LOCK  g_localMqttLock;

static pthread_t g_localMqttThread;





int mqttConnect(){
    int ret = mqtt_connect(&g_local_mqtt, g_local_mqtt_addr, g_local_mqtt_port, g_local_mqtt_username, g_local_mqtt_password, 60);
    if(MOSQ_ERR_SUCCESS == ret){
        log_i("mqtt connect success");
        return mqtt_start(&g_local_mqtt);
    } else {
        log_e("mqtt connect failed");
        mqtt_destroy(&g_local_mqtt);
        return ret;
    }
}
int mqttConnectLoop(){
    while(1){
        if(MOSQ_ERR_SUCCESS == mqttConnect()){
            // threadLockWait(&g_localMqttLock);
            break;
        }
        sleep(2);
    }
    return MOSQ_ERR_SUCCESS;
}

void* mqttThreadConnect(void *arg){
    pthread_detach(pthread_self());
    mqttConnectLoop();
}
    
int localMqttInit(){
    g_local_mqtt.clientId = "";
    g_local_mqtt.callbacks = NULL;
    if(0 != threadLockInit(&g_localMqttLock)){
        log_e("Local mqtt thread lock init failed");
        return MOSQ_ERR_INVAL;
    }
    int ret = mqtt_init(&g_local_mqtt);
    if(MOSQ_ERR_SUCCESS == ret){
        log_i("mqtt init success"); 
        // pthread_create(&g_localMqttThread, NULL, mqttThreadConnect, NULL);
    } else {
        log_e("mqtt init failed");
    }
    return ret;
}

void mqttLocalDestroy(){
    mqtt_destroy(&g_local_mqtt);
}

int mqttCallbackRegister(T_MQTT_CALLBACK *callback){
    if(NULL == callback){
        return -1;
    }
    threadLockLock(&g_localMqttLock);
    g_local_mqtt.callbackTail->next = callback;
    callback->prev = g_local_mqtt.callbackTail;
    g_local_mqtt.callbackTail = callback;
    threadLockUnlock(&g_localMqttLock);
    return 0;
}

int mqttCallbackUnregister(T_MQTT_CALLBACK *callback){
    if(NULL == callback){
        return -1;
    }
    threadLockLock(&g_localMqttLock);
    T_MQTT_CALLBACK *pCB = g_local_mqtt.callbacks;
    while(NULL != pCB){
        if(pCB == callback){
            if(pCB == g_local_mqtt.callbacks){
                g_local_mqtt.callbacks = callback->next;
                g_local_mqtt.callbacks->prev = NULL;
                break;
            } else {
                pCB->prev->next = pCB->next;
                break;
            }
        }
    }
    threadLockUnlock(&g_localMqttLock);
    return 0;
}